package com.jerehedu.myapplication34.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.jerehedu.myapplication34.R;
import com.jerehedu.myapplication34.entrty.Book;

import java.util.List;

/**
 * Created by lenovo on 2016/11/5.
 */
public class ListViewAdapter extends BaseAdapter {
    private List<Book> mData;
    private Context context;

    public ListViewAdapter(Context context, List<Book> mData) {
        this.context = context;
        this.mData = mData;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Book book=mData.get(position);
        ViewHolder viewHolder=null;
        if(convertView==null){
            convertView= LayoutInflater.from(context).inflate(R.layout.list_view_item,null,false);
            viewHolder=new ViewHolder();
            viewHolder.title=(TextView)convertView.findViewById(R.id.title);
            viewHolder.size=(TextView)convertView.findViewById(R.id.size);
            viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);
            convertView.setTag(viewHolder);
        }else{
            viewHolder=(ViewHolder)convertView.getTag();
        }
        viewHolder.title.setText(book.getName());
        viewHolder.size.setText(book.getSize()+"MB");
        if(book.getIsCheck()==1){
            viewHolder.checkBox.setChecked(true);

        }else{
            viewHolder.checkBox.setChecked(false);

        }
        viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(book.getIsCheck()==0){
                    book.setIsCheck(1);
                }else{
                    book.setIsCheck(0);
                }
                notifyDataSetChanged();
            }
        });
        return convertView;
    }

    public class ViewHolder{
        TextView title;
        TextView size;
        CheckBox checkBox;
    }
}
